package com.keshi.openplatform.monitor.event;


import com.sun.mail.util.MailSSLSocketFactory;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

@Component
public class MailEventListener {

    @EventListener
    public void onEvent(EventBean bean) throws Exception {
        //当前的处理方式是发送邮件
        //当前 listener 的主要作用是发送邮件给指定的人  5433708  sgcdmbyxwpglbiic
        //登陆账号,我们必须知道登录的是什么邮箱,用的什么账号

        switch (bean.getEventType()) {
            case OVERTIME:
                Properties properties = new Properties();
                properties.put("mail.host", "smtp.qq.com");//设置我们的服务器地址
                properties.put("mail.transport.protocol", "smtp");//设置邮箱发送的协议
                properties.put("mail.smtp.auth", "true");//设置需要认证
                MailSSLSocketFactory sf = new MailSSLSocketFactory();//创建 ssl 连接的工厂对象
                sf.setTrustAllHosts(true);//信任所有主机
                properties.put("mail.smtp.ssl.enable", "true");//设置开启 ssl
                properties.put("mail.smtp.ssl.socketFactory", sf);//设置对应的工厂对象

                Session session = Session.getDefaultInstance(properties, new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication("5433708@qq.com", "zprhlwcnhevnbhei");
                    }
                });//创建会话

                session.setDebug(true);//控制台会显示一些调试的日志
                Transport transport = session.getTransport();//类似于我们的 sql 中的 statement
                transport.connect("smtp.qq.com", "5433708@qq.com", "zprhlwcnhevnbhei");
                Message message = new MimeMessage(session);//创建消息对象,也就是邮件内容对象

                message.setFrom(new InternetAddress("5433708@qq.com"));//设置对方显示的来自于谁的邮件
                //设置收件人
                message.setRecipients(Message.RecipientType.TO, new InternetAddress[]{new InternetAddress("5433708@qq.com"), new InternetAddress("mr.jackiechan@hotmail.com")});
//                message.setRecipient(Message.RecipientType.TO, new InternetAddress("525111498@qq.com"));//设置收件人
                message.setSubject("接口超时预警邮件");//标题
                message.setContent(bean.getMsg(), "text/html;charset=utf-8");//正文

                transport.sendMessage(message, message.getAllRecipients());

                transport.close();
                break;


        }
    }
}
